from mapping import generate_mapping_artefacts
from datastore.resource import Resource, ResourceDict
from datastore.uri import Uri
import urllib
import unittest


class UploadScriptTest(unittest.TestCase):


    def setUp(self):
        pass


    def tearDown(self):
        pass


    def test_remove_cp1252_characters(self):
        '''Tests all the cp1252_to_ascii mapping'''
        # \x93 and \x94 are non-ascii characters and in the cp1252 
        # character map they are the curly double quotes which look like 66 99 
        text = "\x93True\x94\n\x93False\x94"
        fixed_text = generate_mapping_artefacts.remove_cp1252_characters(text)
        self.assertNotEqual(text, fixed_text)
        self.assertEquals(fixed_text, '''"True"\n"False"''')
        # \x91 and \x92 are non-ascii characters and in the cp1252 
        # character map they are the curly quotes which look like 6 9 
        text = "\x91Alpha\x92" 
        fixed_text = generate_mapping_artefacts.remove_cp1252_characters(text)
        self.assertNotEqual(text, fixed_text)
        self.assertEqual(fixed_text,  "'Alpha'")
        # \x96 is a non-ascii character and in the cp1252 
        # character map it is a dash similar to - 
        text = "AB\x96CD" 
        fixed_text = generate_mapping_artefacts.remove_cp1252_characters(text)
        self.assertNotEqual(text, fixed_text)
        self.assertEqual(fixed_text,  "AB-CD")
    
    def test_check_headers_1(self):
        '''test unexpected number of headers'''
        row = []
        try:
            generate_mapping_artefacts.check_headers(row)
        except Exception as e:
            self.assertEqual(e.args[0], 'Number of headers is unexpected. Expected %d, found %d' % (len(generate_mapping_artefacts.COLUMNS), len(row)))
        else:
            self.fail("Exception expected")
            
    def test_check_headers_2(self):
        '''test unexpected order of the headers'''
        row = generate_mapping_artefacts.COLUMNS.copy()
        modified_index = len(row) / 2
        new_value = "ABCD"
        row[modified_index] = new_value
        try:
            generate_mapping_artefacts.check_headers(row)
        except Exception as e:
            self.assertEqual(e.args[0], "Ordering of headers unexpected. Expected %s, found %s" % (generate_mapping_artefacts.COLUMNS[modified_index], row[modified_index]))
        else:
            self.fail("Exception expected")            

    def test_generate_resource_from_row_1(self):
        '''test storing a row of data in the rs'''
        row = ['App','App_sid006a_Applicant_Address_Details<Country>','Applicant_Address_Details_Country','String','0','1','Country of the Applicant address.','','Refer to SPEAR_LXCOUNTRY.NAME database column.','If SPEAR screen states "Applicant details per Applicant Contact" then SPEAR Adaptor should be populated from the Applicant Contact SPEAR screen fields.','app/$spear_ref#Applicant.Address_Details_Country','','app/$spear_ref#Applicant.Organisation_Name','Exist','','Application/PartyRole(Applicant)/Party(PrimaryApplicant)/Organisation/PostalAddress/CountryName','Country name of the Applicant address.','','Undefined','','','Yes','','']
        rs = generate_mapping_artefacts.generate_resource_from_row(row)
        for key, value in generate_mapping_artefacts.VARIABLES.items():
            expected = row[key]
            value_in_rs = rs.get_var(value)
            self.assertEqual(value_in_rs, expected)
    
    def test_generate_resource_from_row_2(self):
        '''test padding the rest of the variables in a resource with empty strings'''
        row = ['App','App_sid006a_Applicant_Address_Details<Country>','Applicant_Address_Details_Country','String','0','1','Country of the Applicant address.','','Refer to SPEAR_LXCOUNTRY.NAME database column.','If SPEAR screen states "Applicant details per Applicant Contact" then SPEAR Adaptor should be populated from the Applicant Contact SPEAR screen fields.','app/$spear_ref#Applicant.Address_Details_Country','','app/$spear_ref#Applicant.Organisation_Name','Exist','','Application/PartyRole(Applicant)/Party(PrimaryApplicant)/Organisation/PostalAddress/CountryName','Country name of the Applicant address.','','Undefined','','Yes','','']
        rs = generate_mapping_artefacts.generate_resource_from_row(row)
        vars = generate_mapping_artefacts.VARIABLES.keys()
        vars.sort()
        for i in range(len(row)):
            expected = row[i]
            value_in_rs = rs.get_var(generate_mapping_artefacts.VARIABLES[i])
            self.assertEqual(value_in_rs, expected)
        
        # test the rest of the variables are padded with empty strings
        i += 1
        while i < len(generate_mapping_artefacts.VARIABLES):
            value_in_rs = rs.get_var(generate_mapping_artefacts.VARIABLES[i])
            self.assertEqual(value_in_rs, "")
            i += 1

    def test_generate_resource_from_row_3(self):
        '''test dont return a resource if row has no data'''
        row = ["","","","","","","","","","","","","","","","","","","","","","","",""]
        rs = generate_mapping_artefacts.generate_resource_from_row(row)
        self.assertFalse(rs)

    def test_generate_resource_from_row_4(self):
        '''test metadata autoload_suffix is generated using the eDAIS National Path Column'''
        row = ["","","","","","","","","","","","","","","","eDAIS/National/Path","","","","","","","",""]
        rs = generate_mapping_artefacts.generate_resource_from_row(row)
        self.assertEqual(rs.get_metadata(Uri("term:base/build/autoload_suffix")),Uri(urllib.quote(rs.get_var(generate_mapping_artefacts.EDAIS_NATIONAL_PATH))))
            
    def test_update_mapping_index(self):
        '''test updating the mapping index'''
        test_autoload_prefix = Uri("internal:eplanning/mapping")
        test_autoload_suffix = Uri("xyz")
        mapping_index = {}
        mapping_index[generate_mapping_artefacts.QUERYREQUESTPUBLICAPPLICATIONSTATUSQUERY] = []
        mapping_index[generate_mapping_artefacts.REPLYPUBLICSTATUSAPPLICATIONRESPONSE] = []
        mapping_index[generate_mapping_artefacts.DECLARESSAVESTATUSCHANGEAPPLICATIONNOTIFICATION] = []
        mapping_index[generate_mapping_artefacts.RECEIPTACKNOWLEDGEMENTSIGNAL] = []
        mapping_index[generate_mapping_artefacts.RECEIPTEXCEPTIONSIGNAL] = []        
        mapping_res = Resource(type="term:eplanning/mapping/row")
        mapping_res.set_var(generate_mapping_artefacts.QUERYREQUESTPUBLICAPPLICATIONSTATUSQUERY, None)
        mapping_res.set_var(generate_mapping_artefacts.REPLYPUBLICSTATUSAPPLICATIONRESPONSE, "Yes")
        mapping_res.set_var(generate_mapping_artefacts.DECLARESSAVESTATUSCHANGEAPPLICATIONNOTIFICATION, None)
        mapping_res.set_var(generate_mapping_artefacts.RECEIPTACKNOWLEDGEMENTSIGNAL, None)
        mapping_res.set_var(generate_mapping_artefacts.RECEIPTEXCEPTIONSIGNAL, None)
        mapping_res.set_metadata(Uri("term:base/build/autoload_suffix"), test_autoload_suffix) 
        mapping_config_rs = Resource(type="term:base/runtime/configuration")
        definition = ResourceDict()
        definition.autoload_prefix = test_autoload_prefix
        mapping_config_rs.definitions = {'term:eplanning/mapping/row': definition}
        generate_mapping_artefacts.update_mapping_index(mapping_index, mapping_res, mapping_config_rs)
        self.assertTrue(test_autoload_prefix + test_autoload_suffix in mapping_index[generate_mapping_artefacts.REPLYPUBLICSTATUSAPPLICATIONRESPONSE])
    
    def test_create_mapping_index(self):
        '''test create mapping index resource'''
        mapping_index = {}
        mapping_index_rs = generate_mapping_artefacts.create_mapping_index(mapping_index)
        self.assertEqual(mapping_index_rs.get_metadata(Uri("term:base/build/autoload_suffix")), Uri("index"))
        self.assertEqual(mapping_index_rs.mapping_index, mapping_index)
    
if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()